import plugin from '../../../lib/plugins/plugin.js';
import fetch from 'node-fetch';

export class IPLocation extends plugin {
  constructor() {
    super({
      name: 'IP定位',
      dsc: '查询IP地址的地理位置',
      event: 'message',
      priority: 5000,
      rule: [
        {
          reg: '^#花花定位\\s*(\\d+\\.\\d+\\.\\d+\\.\\d+)',
          fnc: 'getLocation',
        },
      ],
    });
  }

  async getLocation(e) {
    let ip = e.msg.match(/\d+\.\d+\.\d+\.\d+/)[0];
    let url = `https://api.gmit.vip/Api/IP?format=json&ip=${ip}`;

    try {
      const response = await fetch(url);
      const data = await response.json();
      let location = '';
      if (data.ret === 200) {
        location = `IP地址：${data.data.ip}\n地理位置：${data.data.addr}`;
      } else {
        location = '查询失败，无法获取IP地址的地理位置';
      }
      await this.reply(location, true, { recallMsg: 30 });
    } catch (error) {
      console.error('[IP定位] 接口请求失败:', error);
      await this.reply('IP定位接口请求失败，请联系主人更换接口');
    }
  }
}